package com.crazybytex.modbus;

import com.crazybytex.modbus.service.BatteryService;
import com.crazybytex.modbus.util.SerialPortParameter;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.serial.SerialPortWrapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ModbusApplication {

    public static void main(String[] args) {
        SpringApplication.run(ModbusApplication.class, args);
        modbusInit();
    }

    //初始化modbus
    //实际项目中,可以init之后,ModbusMaster 保存下来,后面直接使用即可
    public static void modbusInit() {

        //参数设置
        SerialPortParameter serialPortParameter = new SerialPortParameter("COM3");

        //modbus 的串口实现类 实现SerialPortWrapper
        SerialPortWrapper serialPortWrapper = new SerialPortWrapperImpl(serialPortParameter);
        //构造master(client端)
        ModbusFactory modbusFactory = new ModbusFactory();
        //RTU Master
        ModbusMaster client = modbusFactory.createRtuMaster(serialPortWrapper);
        try {
            client.init();
         //   client.destroy();
        } catch (Exception e) {

        }
        // 从站设备ID是1
        int slaveId = 1;


        //测试方法
        BatteryService batteryService = new BatteryService();
       batteryService.getLoadVoltageAndCurrent(client,slaveId);

    }
}
